<template>
  <el-cascader
    class="wp100"
    @change="onChange"
    change-on-select
    :options="options"
    :props="props"
    v-model="areaArry"
    :clearable="clearable"
  ></el-cascader>
</template>

<script>
export default {
  components: {},
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    },
    clearable: {
      type: Boolean,
      default: true
    },
    showLevel: {
      type: Number,
      default: 2,
      validator (value) {
        return [1, 2, 3].includes(value)
      }
    },
    reload: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      areaArry: [],
      provinceList: [],
      cityList: [],
      areaList: [],
      isEdit: true,
      props: {
        value: 'concatId',
        label: 'regionName',
        children: 'children'
      },
      options: [],
      provinceSelected: {},
      citySelected: {},
      areaSelected: {}
    }
  },
  computed: {
    cloneValue: {
      get () {
        return this.value
      },
      set (value) {
      }
    }
  },
  watch: {
    cloneValue: {
      handler (value) {
        if (!value.provinceId) this.areaArry = []
      },
      immediate: true,
      deep: true
    },
    async reload (val) {
      if (val) {
        await this.getProvinceList()
        if (this.value.provinceId) {
          this.backArea(this.value)
        }
        this.$emit('finish-reload')
      }
    }
  },
  async mounted () {
    await this.getProvinceList()
    if (this.cloneValue.provinceId) {
      this.backArea(this.cloneValue)
    }
  },
  methods: {
    handlerProvinceChange (orgCode) {
      this.getCityList(orgCode)
    },
    async getList (regionLevel = 1, pId) {
      let res = await this.$apis.region.getTreeChildren({ regionLevel, pId, maxRegionLevel: this.showLevel })
      return res
    },
    // 省市区回填
    async backArea (val) {
      let isEmptyObject = !!Object.keys(val).length
      if (typeof val === 'object' && isEmptyObject) {
        let provinceIndex, cityIndex, areaIndex
        if (val.provinceId) {
          await this.getCityList(val.provinceId)
          provinceIndex = this.provinceList.findIndex(item => {
            return +item.id === +val.provinceId
          })
          this.options[provinceIndex].children = this.cityList
          this.provinceSelected = [
            val['provinceId'],
            val['provinceName'],
            provinceIndex
          ]
          this.areaArry.splice(0, 1, this.provinceSelected.join('-'))
        }
        if (val.cityId) {
          await this.getAreaList(val.cityId)
          cityIndex = this.cityList.findIndex(item => {
            return +item.id === +val.cityId
          })
          this.options[provinceIndex].children[cityIndex].children = this.areaList
          this.citySelected = [
            val['cityId'] === 0 ? '' : val['cityId'],
            val['cityName'],
            cityIndex
          ]
          this.areaArry.splice(1, 1, this.citySelected.join('-'))
        }
        if (val.areaId) {
          areaIndex = this.areaList.findIndex(item => {
            return +item.id === +val.areaId
          })
          this.areaSelected = [
            val['areaId'] === 0 ? '' : val['areaId'],
            val['areaName'],
            areaIndex
          ]
          this.areaArry.splice(2, 1, this.areaSelected.join('-'))
        }
        this.isEdit = false
      }
    },
    async onChange (val) {
      await this.setSelected(val)
      this.$emit('input', {
        provinceId: this.provinceSelected[0] || '',
        provinceName: this.provinceSelected[1] || '',
        cityId: this.citySelected[0] || '',
        cityName: this.citySelected[1] || '',
        areaId: this.areaSelected[0] || '',
        areaName: this.areaSelected[1] || ''
      })
    },
    async setSelected (val) {
      this.provinceSelected = (val[0] && val[0].split('-')) || []
      this.citySelected = (val[1] && val[1].split('-')) || []
      this.areaSelected = (val[2] && val[2].split('-')) || []
      if (val[0] && this.showLevel >= 2) {
        await this.getCityList(this.provinceSelected[0])
        this.options[this.provinceSelected[2]].children = this.cityList
      }
      if (val[1] && this.showLevel === 3) {
        await this.getAreaList(this.citySelected[0])
        this.options[this.provinceSelected[2]].children[this.citySelected[2]].children = this.areaList
      }
    },
    async getProvinceList () {
      let res = await this.getList(1, '-1')
      this.provinceList = this.mapItem(res)
      let _opt = JSON.stringify(this.provinceList)
      this.options = JSON.parse(_opt)
    },
    async getCityList (provinceId) {
      let res = await this.getList(2, provinceId)
      this.cityList = this.mapItem(res, false)
    },
    async getAreaList (cityId) {
      let res = await this.getList(3, cityId)
      this.areaList = this.mapItem(res, false)
    },
    mapItem (res, addChildren = true) {
      return res.map((item, index) => {
        return {
          index,
          ...item,
          concatId: `${item.id}-${item.regionName}-${index}`
        }
        // return _item
        // if (!addChildren) {
        //   return _item
        // } else {
        //   return {
        //     children: [],
        //     ..._item
        //   }
        // }
      })
    }
  }
}
</script>

<style>
</style>
